// packageE/form/form.js
var app = getApp();
Component({
  properties: {
    datas: {
      type: null,
    },
    component_id: {
      type: null,
    },
  },
  // 私有数据，可用于模板渲染
  data: {
    emptyImage:  `${app.globalData.imgPath}image.png`,
    clientWidth: "375",

    status: 0, // 是否已提交
    startDate: new Date(1923, 1, 1).getTime(),
    Height: "",
    formList: [],
    showAddress: false,
    form_id: "",
    shoTime: "",
    types: {
      88: "diyusername",
      99: "diypassword",
      0: "diyinput",
      1: "diytextarea",
      3: "diycheckbox",
      4: "diyradio",
      2: "diyselect",
      7: "diydate",
      9: "diycity",
      5: "diyimage",
    },
    diydata: [],
    setname: "",
    uploadUrl: "upload.uploadPic",
    //地区
    provinceData: [],
    cityData: [],
    districtData: [],
    pickerValue: [0, 0, 0],
    selectAddressData: [],
    currentDate: new Date().getTime(),
    showCity1: false,
    imgPath: app.globalData.imgPath,
  },

  lifetimes: {
    // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
    attached() {
      console.log(this.properties.datas);
    },
    moved() {},
    detached() {},
  },

  // 生命周期函数，可以为函数，或一个在methods段中定义的方法名
  attached() {},
  // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready() {
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });

    this._initAddressInfo();
    if (this.data.datas.form.title) {
      this.getForm(this.data.datas.list);
    }
  },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show() {},
    hide() {},
    resize() {},
  },
  methods: {
    // 再次提交
    againSubmit(e,_id=''){
      console.log(_id,'ddddddddddddddddddd')
      let that = this;
      let urlStr = app.getNetAddresss(
        "plugin.diyform.api.diy-form.getDiyFormTypeMemberData"
      );
      let form_id = _id?_id:(this.data.datas.form_id?this.data.datas.form_id:this.data.datas.form.id)
      urlStr +=
        "&form_id=" + form_id;
      app._getNetWork({
        url: urlStr,
        success: (resdata)=> {
          var res = resdata.data;
          if (res.result == 1) {
            if(_id){
              if(res.data.status === 1){
                that.setData({
                  formList:[],
                  diyform: res.data,
                  thumb: res.data.thumb,
                  status:res.data.status
                });
                const fields = that.data.diyform.fields;
                for (let field in fields) {
                  var list = {
                    title: fields[field].tp_name,
                    value: fields[field].value,
                    data_type: fields[field].data_type,
                    tp_must: fields[field].tp_must,
                  };
                  if (list.data_type == "3") {
                    list.value = fields[field].value.join(",");
                  }
                  that.data.formList.push(list);
                  that.setData({
                    formList: that.data.formList,
                  });
                }
                console.log(this.data.formList,'formList')
                return
              }
            }
            that.setData({
              status: 0,
              loading: true,
              diyform: res.data,
              diydata:[]
            });
            
            let fields = that.data.diyform.fields;
            let diydata = that.data.diydata;
            let f = null;
            for (var field in fields) {
              if (fields[field].data_type == 7) {
                var timestamp = Date.parse(new Date());
                var date = new Date(timestamp);
                //获取年份
                var Y = date.getFullYear();
                //获取月份
                var M =
                  date.getMonth() + 1 < 10
                    ? "0" + (date.getMonth() + 1)
                    : date.getMonth() + 1;
                //获取当日日期
                var D =
                  date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
                console.log(Y + "-" + M + "-" + D);
                var isdatae = Y + "-" + M + "-" + D;
                f = {
                  name: field,
                  data: fields[field],
                  value: fields[field].default_time,
                  type: that.data.types[fields[field].data_type],
                };
              }
              if (that.data.types[fields[field].data_type] == "diycheckbox") {
                f = {
                  name: field,
                  data: fields[field],
                  value: [],
                  type: that.data.types[fields[field].data_type],
                };
              } else if (
                that.data.types[fields[field].data_type] == "diyselect"
              ) {
                let tp_textArr = [];
                for (let i = 0; i < fields[field].tp_text.length; i++) {
                  tp_textArr.push({
                    name: fields[field].tp_text[i],
                  });
                }
                f = {
                  name: field,
                  data: fields[field],
                  value: "",
                  type: that.data.types[fields[field].data_type],
                  diysishow: false,
                  sitem: tp_textArr,
                };
              } else if (
                that.data.types[fields[field].data_type] == "diycity"
              ) {
                f = {
                  name: field,
                  data: fields[field],
                  value: "",
                  type: that.data.types[fields[field].data_type],
                  showAdd: false,
                };
              } else if (
                that.data.types[fields[field].data_type] == "diydate"
              ) {
                console.log(fields[field].default_time)
                f = {
                  name: field,
                  data: fields[field],
                  value: "",
                  type: that.data.types[fields[field].data_type],
                  timeShow: false,
                  currentDate: new Date().getTime(),
                  shoTime: fields[field].default_time
                    ? fields[field].default_time
                    : isdatae,
                };
              } else if (
                that.data.types[fields[field].data_type] == "diyimage"
              ) {
                f = {
                  name: field,
                  data: fields[field],
                  imgUrls: [],
                  isPhoto: false,
                  type: that.data.types[fields[field].data_type],
                };
              } else {
                f = {
                  name: field,
                  data: fields[field],
                  value: "",
                  type: that.data.types[fields[field].data_type],
                };
              }
              console.log(that.data.diydata)
              diydata.push(f);
              that.setData({
                diydata: diydata,
              });
            }
            
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //获取表单信息
    getForm(data) {
      let that = this;

      this.setData({
        form_id: this.data.datas.list.id,
      });

      if (data) {
        that.setData({
          status: data.status,
          loading: true,
        });
        if (that.data.status === 1) {
          that.setData({
            diyform: data,
          });
          const fields = that.data.diyform.fields;
          for (let field in fields) {
            var list = {
              title: fields[field].tp_name,
              value: fields[field].value,
              data_type: fields[field].data_type,
              tp_must: fields[field].tp_must,
            };
            if (list.data_type == "3") {
              list.value = fields[field].value?fields[field].value.join(","):"";
            }
            if (list.data_type == "7") {
              list.value = fields[field].value;
            }
            if (list.data_type == "1") {
              list.value = fields[field].value;
            }
            that.data.formList.push(list);
            that.setData({
              formList: that.data.formList,
            });
          }
        } else {
          that.setData({
            diyform: data,
          });
          let fields = that.data.diyform.fields;
          let diydata = that.data.diydata;
          let f = null;
          for (var field in fields) {
            if (that.data.types[fields[field].data_type] == "diycheckbox") {
              f = {
                name: field,
                data: fields[field],
                value: [],
                type: that.data.types[fields[field].data_type],
              };
            }
            // else if (that.data.types[fields[field].data_type] == "diydate") {
            //   f = {
            //     name: field,
            //     data: fields[field],
            //     value: "",
            //     type: that.data.types[fields[field].data_type],
            //   };
            // }
            else if (that.data.types[fields[field].data_type] == "diyselect") {
              let tp_textArr = [];
              for (let i = 0; i < fields[field].tp_text.length; i++) {
                tp_textArr.push({
                  name: fields[field].tp_text[i],
                });
              }
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                diysishow: false,
                sitem: tp_textArr,
              };
            } else if (that.data.types[fields[field].data_type] == "diycity") {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                showAdd: false,
              };
            } else if (that.data.types[fields[field].data_type] == "diydate") {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
                timeShow: false,
                currentDate: new Date().getTime(),
              };
            } else if (that.data.types[fields[field].data_type] == "diyimage") {
              f = {
                name: field,
                data: fields[field],
                imgUrls: [],
                isPhoto: false,
                type: that.data.types[fields[field].data_type],
              };
            } else {
              f = {
                name: field,
                data: fields[field],
                value: "",
                type: that.data.types[fields[field].data_type],
              };
            }
            diydata.push(f);
            that.setData({
              diydata: diydata,
            });
          }
        }
      }
    },
    getFormBack(_id) {
      let that = this;
      let urlStr = app.getNetAddresss(
        "plugin.diyform.api.diy-form.getDiyFormTypeMemberData"
      );
      let form_id = _id?_id:(this.data.datas.form_id?this.data.datas.form_id:this.data.datas.form.id)
      urlStr +=
        "&form_id=" + form_id;
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              status: res.data.status,
              loading: true,
            });
            if (that.data.status === 1) {
              that.setData({
                diyform: res.data,
                thumb: res.data.thumb,
              });
              const fields = that.data.diyform.fields;
              for (let field in fields) {
                var list = {
                  title: fields[field].tp_name,
                  value: fields[field].value,
                  data_type: fields[field].data_type,
                  tp_must: fields[field].tp_must,
                };
                if (list.data_type == "3") {
                  list.value = fields[field].value.join(",");
                }
                that.data.formList.push(list);
                that.setData({
                  formList: that.data.formList,
                });
              }
            } else {
              that.setData({
                diyform: res.data,
              });
              let fields = that.data.diyform.fields;
              let diydata = that.data.diydata;
              let f = null;
              for (var field in fields) {
                if (that.data.types[fields[field].data_type] == "diycheckbox") {
                  f = {
                    name: field,
                    data: fields[field],
                    value: [],
                    type: that.data.types[fields[field].data_type],
                  };
                }
                // else if (
                //   that.data.types[fields[field].data_type] == "diydate"
                // ) {
                //   f = {
                //     name: field,
                //     data: fields[field],
                //     value: "",
                //     type: that.data.types[fields[field].data_type],
                //   };
                // }
                else if (
                  that.data.types[fields[field].data_type] == "diyselect"
                ) {
                  let tp_textArr = [];
                  for (let i = 0; i < fields[field].tp_text.length; i++) {
                    tp_textArr.push({
                      name: fields[field].tp_text[i],
                    });
                  }
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    diysishow: false,
                    sitem: tp_textArr,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diycity"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    showAdd: false,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diydate"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                    timeShow: false,
                    currentDate: new Date().getTime(),
                    shoTime: fields[field].default_time
                      ? fields[field].default_time
                      : isdatae,
                  };
                } else if (
                  that.data.types[fields[field].data_type] == "diyimage"
                ) {
                  f = {
                    name: field,
                    data: fields[field],
                    imgUrls: [],
                    isPhoto: false,
                    type: that.data.types[fields[field].data_type],
                  };
                } else {
                  f = {
                    name: field,
                    data: fields[field],
                    value: "",
                    type: that.data.types[fields[field].data_type],
                  };
                }
                diydata.push(f);
                that.setData({
                  diydata: diydata,
                });
              }
            }
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    },
    //自定义表单值绑定
    tpnameinp(e) {
      let val = e.detail.value;
      let idx = e.currentTarget.dataset.idex;

      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    onRead_1(e) {
      let name = e.currentTarget.dataset.name;
      this.setData({
        setname: name,
      });
      let that = this;
      let urlStr = app.getNetAddresss(this.data.uploadUrl);
      wx.chooseImage({
        count: 1,
        sizeType: ["original", "compressed"],
        sourceType: ["album", "camera"],
        success(res) {
          const tempFilePaths = res.tempFilePaths;
          wx.compressImage({
            src: tempFilePaths[0], // 图片路径
            quality: 60, // 压缩质量
            success(e) {
              let photourl = e.tempFilePath;

              wx.uploadFile({
                url: urlStr,
                filePath: photourl,
                name: "file",
                formData: {
                  attach: that.data.setname,
                },
                success(resdata) {
                  var res = JSON.parse(resdata.data);
                  if (res.result == 1) {
                    let diydata = that.data.diydata;
                    for (var i = 0; i < diydata.length; i++) {
                      if (diydata[i].name == res.data.attach) {
                        diydata[i].imgUrls.push(res.data.img_url);
                      }
                    }
                    that.setData({
                      diydata: diydata,
                    });
                  } else {
                    wx.showToast({
                      icon: "none",
                      title: res.msg,
                      duration: 1500,
                    });
                  }
                },
              });
            },
            fail(e) {
              console.log(e);
            },
            complete(e) {},
          });
        },
      });
    },
    removeImg: function (e) {
      let delIndex = e.currentTarget.dataset.indexc;
      let index_1 = e.currentTarget.dataset.index;
      let diydata = this.data.diydata;
      diydata[index_1].imgUrls.splice(delIndex, 1);
      this.setData({
        diydata: diydata,
      });
    },
    diytextareainp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value.value"]: val,
      });
    },
    checkboxinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    diyselectBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: true,
      });
    },
    raidinp(e) {
      let val = e.detail;
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
      });
    },
    //所在地选择显示
    showAddBtn(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: true,
      });
    },
    // 关闭选择收货地址
    _closeDateLw: function (e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //地址选择器数据初始化
    _initAddressInfo: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          that._getProvinceData();
        },
        fail: function (res) {
          app._getNetWork({
            url: app.getNetAddresss("member.member-address.address"),
            success: function (res) {
              var response = res.data;
              var province = response.data.province;
              var city = response.data.city;
              var district = response.data.district;
              wx.setStorage({
                key: "provinceData",
                data: province,
              });
              wx.setStorage({
                key: "cityData",
                data: city,
              });
              wx.setStorage({
                key: "districtData",
                data: district,
              });
              that._initAddressInfo();
            },
            fail: function (res) {},
            state: true,
          });
        },
      });
    },
    // 读取省key
    _getProvinceData: function () {
      var that = this;
      var _keyName = "provinceData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          that.setData({
            provinceData: res.data,
          });
          that.setData({
            "selectAddressData[0].name":
              res.data[that.data.pickerValue[0]].areaname,
            "selectAddressData[0].id": res.data[that.data.pickerValue[0]].id,
            "selectAddressData[0].index": that.data.pickerValue[0],
          });
          that._getCityData();
        },
      });
    },
    // 读取城市key，筛选城市data
    _getCityData: function () {
      var _data = this.data.selectAddressData[0];
      var that = this;
      var _keyName = "cityData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            cityData: _json,
          });
          that.setData({
            "selectAddressData[1].name":
              _json[that.data.pickerValue[1]].areaname,
            "selectAddressData[1].id": _json[that.data.pickerValue[1]].id,
            "selectAddressData[1].index": that.data.pickerValue[1],
          });
          that._getDistrictData();
        },
      });
    },
    // 读取地区key，筛选地区data
    _getDistrictData: function () {
      var _data = this.data.selectAddressData[1];
      var that = this;
      var _keyName = "districtData";
      wx.getStorage({
        key: _keyName,
        success: function (res) {
          var _json = [];
          for (var i = 0; i < res.data.length; i++) {
            if (res.data[i].parentid == _data.id) {
              _json.push(res.data[i]);
            }
          }
          that.setData({
            districtData: _json,
          });
          that.setData({
            "selectAddressData[2].name":
              _json[that.data.pickerValue[2]].areaname,
            "selectAddressData[2].id": _json[that.data.pickerValue[2]].id,
            "selectAddressData[2].index": that.data.pickerValue[2],
          });
        },
      });
    },
    // 收货地址滚动事件
    bindChange: function (e) {
      var val = e.detail.value;
      if (this.data.pickerValue[0] != val[0]) {
        val[1] = 0;
        val[2] = 0;
      }
      if (this.data.pickerValue[1] != val[1]) {
        val[2] = 0;
      }
      this.setData({
        "pickerValue[0]": val[0],
        "pickerValue[1]": val[1],
        "pickerValue[2]": val[2],
      });
      this._initAddressInfo();
    },
    //城市结果
    resultAdd: function (e) {
      let idx = e.currentTarget.dataset.idex;
      let seleData = this.data.selectAddressData;
      let retCity =
        seleData[0].name + " " + seleData[1].name + " " + seleData[2].name;
      this.setData({
        ["diydata[" + idx + "].value"]: retCity,
        ["diydata[" + idx + "].showAdd"]: false,
      });
    },
    //自定义日期选择
    openPicker(e) {
      let idx = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + idx + "].timeShow"]: true,
      });
    },
    _closeDateLw_1() {
      this.setData({
        showCity1: false,
      });
    },
    resultAdd_1() {
      let seleData = this.data.selectAddressData;
      this.setData({
        "applyModel.province_name": seleData[0].name,
        "applyModel.city_name": seleData[1].name,
        "applyModel.district_name": seleData[2].name,
        fullAddress:
          seleData[0].name + " " + seleData[1].name + " " + seleData[2].name,
        showCity1: false,
      });
    },
    submit() {
      this.validation();
      if (!this.data.isValidation) {
        return;
      }
      this.submitForm();
    },
    validation() {
      this.setData({
        isValidation: true,
      });
      this.data.diydata.forEach((item) => {
        if (item.data.tp_must == 1 && !item.value && item.type != "diyimage") {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须填写哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
        if (item.data.tp_must == 1 && item.type == "diyimage") {
          if (item.imgUrls.length < item.data.tp_max) {
            wx.showToast({
              icon: "none",
              title: item.data.tp_name + "必须上传" + item.data.tp_max + "张",
              duration: 1500,
            });
            this.setData({
              isValidation: false,
            });
          }
        }
        if (item.type == "diycheckbox" && item.value.length == 0) {
          wx.showToast({
            icon: "none",
            title: item.data.tp_name + "必须选择哦",
            duration: 1500,
          });
          this.setData({
            isValidation: false,
          });
        }
      });
    },
    //自定义表单提交
    submitForm() {
      var that = this;
      var formData = [];
      var formObject = {};
      console.log(this.data.diydata,'dwwwwwwwwww')
      this.data.diydata.forEach((item) => {
        //图片类型的直接提交图片base64的数组到后台，其它直接传值
        if (item.type == "diyimage") {
          formObject[item.name] = item.imgUrls;
        } else {
          formObject[item.name] = item.value;
        }

        if (item.type == "diydate") {
          formObject[item.name] = !app._isTextEmpty(item.value)
            ? that.timestampToTime(item.value * 1000)
            : item.shoTime;
        }
      });
      formData.push(formObject);
      let json = {
        form_id: this.data.datas.form_id
          ? this.data.datas.form_id
          : this.data.datas.form.id,
        form_data: formData,
      };
      let urlStr = app.getNetAddresss(
        "plugin.diyform.api.diy-form.save-form-data"
      );
      app._postNetWork({
        url: urlStr,
        showToastIn: false,
        data: json,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            wx.showModal({
              title: '提示',
              content: '提交成功',
              showCancel: false,
              success (response) {
                if (response.confirm) {
                  if(that.properties.datas.list && that.properties.datas.list.resubmit == 1){
                    // 装修表单再次提交数据回显
                    that.againSubmit('',res.data.form_id)
                    return
                  }
                  that.getFormBack(res.data.form_id);
                }
              }
            })
          } else {
            wx.showToast({
              icon: "none",
              title: res.msg,
              duration: 1500,
            });
          }
        },
        fail: function (res) {},
      });
    },
    showCity1btn() {
      this.setData({
        showCity1: true,
      });
    },
    sitemSelectBtn(e) {
      let val = e.detail.name;
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].value"]: val,
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    sitemClose(e) {
      let idx = e.currentTarget.dataset.index;
      this.setData({
        ["diydata[" + idx + "].diysishow"]: false,
      });
    },
    dateClose(e) {
      let index = e.currentTarget.dataset.idex;
      this.setData({
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
    //日期转化
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      let Y = date.getFullYear() + "-";
      let M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      let D = this.change(date.getDate()) + " ";
      return Y + M + D;
    },
    change(t) {
      if (t < 10) {
        return "0" + t;
      } else {
        return t;
      }
    },
    birthdayconfirm(e, time) {
      let index = e.currentTarget.dataset.idex;
      let val = e.detail;
      this.setData({
        ["diydata[" + index + "].value"]: String(val).substring(0, 10),
        ["diydata[" + index + "].shoTime"]: this.timestampToTime(val),
        ["diydata[" + index + "].timeShow"]: false,
      });
    },
  },
});
